rm(list=ls())
setwd('put_your_wd_here')

pacman::p_load(lubridate, tidyverse, haven, gtrendsR, 
               rdrobust, rddtools,
               broom, ggpubr, gridExtra,readxl)

getDat <- function(term, date){
   cut = lubridate::ymd(date)
   start_date = cut - months(2)
   end_date = cut + months(2)
   time_span = paste(start_date, end_date, sep=' ')
   res <- gtrends(term,geo='US',
                  low_search_volume = T,
                  time = time_span,
                  onlyInterest = TRUE)
   dat <- res$interest_over_time
   dat$date <- ymd(dat$date)
   dat$running_day <- as.numeric(dat$date - ymd(date))
   dat$hits <- as.numeric(dat$hits)
   dat$hits[is.na(dat$hits)] <- 0
   return(dat)
 }

makePlot <- function(input_date){
  
  datcontrol <- getDat(date=input_date,term = 'Gun Control') %>%
    mutate(running_day = as.numeric(
      date - ymd(input_date)
    ))
  
  control <- rdplot(datcontrol$hits, 
                    x=datcontrol$running_day, 
                    c=0, p=1)
  control$vars_bins$outcome <- '"Gun Control"'
  control$vars_poly$outcome <- '"Gun Control"'

  datrights <- getDat(date=input_date,term = 'Gun Rights') %>%
    mutate(running_day = as.numeric(
      date - ymd(input_date)
    ))
  
  rights <- rdplot(datrights$hits, 
                   x=datrights$running_day, 
                   c=0, p=1)
  rights$vars_bins$outcome <- '"Gun Rights"'
  rights$vars_poly$outcome <- '"Gun Rights"'

  points <- bind_rows(control$vars_bins, rights$vars_bins)
  lines <- bind_rows(control$vars_poly, rights$vars_poly)

  plot <- bind_rows(datcontrol,datrights) %>%
    rename(outcome=keyword) %>%
    mutate(outcome = case_when(
      outcome == "Gun Control" ~ '"Gun Control"',
      outcome == "Gun Rights" ~ '"Gun Rights"'
    )) %>%
    ggplot(aes(x=running_day, y=hits)) +
    geom_point(fill='white', size=1, shape=21, color='grey30') +
    theme_bw() +
    geom_vline(xintercept=0, linetype=2, color='red') +
    labs(x='Day',y='Google Search Activity') +
    geom_line(data=lines[lines$rdplot_x < 0,], aes(x=rdplot_x, y=rdplot_y)) +
    geom_line(data=lines[lines$rdplot_x > 0,], aes(x=rdplot_x, y=rdplot_y)) +
    facet_wrap(~outcome)
  return(plot)
}
plot.out <- makePlot('2018-02-14') +
  labs(title='(A) Sample RDiT Plot',x='Days', 
       y='Google Search Activity') +
  theme(plot.title = element_text(hjust = 0.5)) 
ggsave(plot.out, width=8, height=3, 
       file='figures/sample_rdit_plot.png')
